package cn.john.basic.controller;

import cn.john.basic.util.AjaxResult;
import cn.john.basic.util.FastDfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 *  1.上传
 *  2.删除
 *  3.修改 = 删除 + 上传
 */
@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    /**
     * @RequestPart: 接收文件
     * required = true ： 必传
     * value = "file" ： 接口名称是file的参数
     *
     * @param file
     * @return
     */
    @PostMapping
    public AjaxResult upload(@RequestPart(required = true,value = "file") MultipartFile file) {
        // 获取扩展名
        try {
            String filename = file.getOriginalFilename();
            String extName = filename.substring(filename.lastIndexOf(".") + 1);
            String path = FastDfsUtil.upload(file.getBytes(), extName);
            return new AjaxResult().setResultObj(path);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.setMessage();
        }
    }

    /**
     * 删除接口
     * @param path
     * @return
     */
    @DeleteMapping
    public AjaxResult delete(@RequestParam(required = true,value = "path") String path) {
        try {
            String pathTmp = path.substring(1);
            String groupName = pathTmp.substring(0, pathTmp.indexOf("/"));
            String remotePath = pathTmp.substring(pathTmp.indexOf("/") + 1);
            FastDfsUtil.delete(groupName, remotePath);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.setMessage();
        }
    }
}
